from sanic import Sanic
from mongoengine import connect

from .views.api_bp import bp as api_bp
from .views.api_view import SimapleAsyncView
from .views.user_api import UserAsyncListCreateApi, \
    UserAsyncRetrieveUpdateDestroyApi

app = Sanic(__name__)


@app.middleware('request')
async def log_request(request):
    request.headers.add('Access-Control-Allow-Origin', '*')
    request.headers.add('Access-Control-Allow-Headers', '*')
    request.headers.add('Access-Control-Allow-Methods',
                        'GET,POST,PUT,HEAD,OPTIONS,PATCH,DELETE')


@app.middleware('response')
async def log_response(request, response):
    pass


@app.listener('before_server_start')
async def setup_db(app, loop):
    connect("sanic", host="localhost", port=27017)


app.blueprint(api_bp)
app.add_route(SimapleAsyncView.as_view(), '/api/v1/view')

app.add_route(UserAsyncListCreateApi.as_view(), '/api/v1/user')
app.add_route(UserAsyncRetrieveUpdateDestroyApi.as_view(),
              '/api/v1/user/<pk>')
